﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace RiaToDalLinq.ProviderBase
{
    /// <summary>
    /// 
    /// </summary>
    internal class SubtreeEvaluator : ExpressionVisitor
    {
        HashSet<Expression> _candidates;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="candidates"></param>
        internal SubtreeEvaluator(HashSet<Expression> candidates)
        {
            _candidates = candidates;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="exp"></param>
        /// <returns></returns>
        internal Expression Eval(Expression exp)
        {
            return this.Visit(exp);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="exp"></param>
        /// <returns></returns>
        protected override Expression VisitExtension(Expression exp)
        {
            if (exp == null)
            {
                return null;
            }

            if (this._candidates.Contains(exp))
            {
                return this.Evaluate(exp);
            }

            return base.Visit(exp);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        private Expression Evaluate(Expression e)
        {
            if (e.NodeType == ExpressionType.Constant)
            {
                return e;
            }

            LambdaExpression lambda = Expression.Lambda(e);
            Delegate func = lambda.Compile();
            return Expression.Constant(func.DynamicInvoke(null), e.Type);
        }
    }
}
